//
//  CityList.m
//  PCN
//
//  Created by 蒙奇D路飞 on 16/8/2.
//  Copyright © 2016年 com.smh.pcn. All rights reserved.
//

#import "CityList.h"
#import "CityCollectionCell.h"
#import "CityCollectionHeadView.h"
#import "ZYPinYinSearch.h"
#import "LocationCityModel.h"

//#import <CoreLocation/CoreLocation.h>
#import "CommonDefine.h"
#import <BMKLocationkit/BMKLocationComponent.h>
//#import <BaiduMapAPI_Map/BMKMapComponent.h>

@interface CityList ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,BMKLocationManagerDelegate,BMKLocationAuthDelegate>{
    //,CLLocationManagerDelegate
    
    NSMutableArray *allCities;
    NSMutableArray *allCityNames;
    NSArray *hostCities;
    NSString *currentLocationCityName;
    BOOL isLocationFail;
    BOOL isLocating;
}
@property (nonatomic,strong) UITableView *mainTable;
@property (assign, nonatomic) BOOL isSearch;
@property (nonatomic,strong) UISearchBar *searchBar;
@property (nonatomic,strong) NSArray *data;
@property (nonatomic,strong) NSMutableArray *searchData;
@property (nonatomic,strong) UICollectionView *collectionView;

//@property (nonatomic,strong) CLLocationManager *locManager;//获取用户位置
//@property(nonatomic,strong) CLGeocoder *geocoder;//反地理编码
@property(nonatomic, strong) BMKLocationManager *locationManager;
@property(nonatomic, copy) BMKLocatingCompletionBlock completionBlock;


@end

@implementation CityList

static NSString *collectionCellID = @"collectionCellID";
static NSString *collectionHeadID = @"collectionHeadID";

-(NSArray *)data{
    if (!_data) {
        _data = [[NSArray alloc]initWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"PeanutEbuyCity" ofType:@"plist"]];
    }
    return _data;
}
-(UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth- 20, (hostCities.count/3==0?hostCities.count/3:hostCities.count/3+1)*40 + 40 + 60) collectionViewLayout:flowLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor mainBackgroundColor];
    }
    return _collectionView;
}
-(void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    self.navigationController.navigationBarHidden = NO; // 使右滑返回手势可用

}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"选择城市";
    self.view.backgroundColor = [UIColor mainBackgroundColor];;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self showBarButton:NAV_LEFT title:@"关闭" fontColor:[UIColor blackColor]];
    [self setUpUI];
     [[BMKLocationAuth sharedInstance] checkPermisionWithKey:@"ib2XIVRA4fAUx4FLUBI0ZGVmV7GdFO0R" authDelegate:self];
    
    [self initBlock];
    [self initLocation];
    [_locationManager requestLocationWithReGeocode:YES withNetworkState:YES completionBlock:self.completionBlock];
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    
    [_locationManager stopUpdatingLocation];
    _locationManager.delegate = nil;
}

-(void)setUpUI{
    allCities = [NSMutableArray new];
       hostCities = [NSArray new];
       allCityNames = [NSMutableArray new];
       isLocating = NO;
       for (NSDictionary *dic in self.data) {
           if (![dic[@"title"] isEqualToString:@"热门"]) {
              NSArray * tempArray =  [LocationCityModel mj_objectArrayWithKeyValuesArray:dic[@"cities"]];
                 for (LocationCityModel *model in tempArray) {
                     [allCityNames addObject:model];
                 }
               [allCities addObject:dic];
           }else{
               hostCities = [LocationCityModel mj_objectArrayWithKeyValuesArray:dic[@"cities"]];
           }
       }
       [self.collectionView registerClass:[CityCollectionCell class] forCellWithReuseIdentifier:collectionCellID];
       [self.collectionView registerClass:[CityCollectionHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:collectionHeadID];
       
       self.mainTable.sectionIndexBackgroundColor = [UIColor clearColor];
       self.searchData = [NSMutableArray new];
       //设置搜索框
       self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
       self.searchBar.delegate = self;
       self.searchBar.placeholder = @"输入城市名或拼音";
       self.searchBar.textFieldSearchBar.searchTextField.font = [UIFont systemFontOfSize:13];
       self.searchBar.textFieldSearchBar.searchTextField.backgroundColor = [UIColor whiteColor];
       self.searchBar.textFieldSearchBar.searchTextField.layer.borderColor = [UIColor blackColor].CGColor;
       self.searchBar.textFieldSearchBar.searchTextField.layer.borderWidth = 0.5;
       self.searchBar.textFieldSearchBar.searchTextField.layer.cornerRadius = self.searchBar.textFieldSearchBar.height/2;
       self.searchBar.textFieldSearchBar.layer.masksToBounds = YES;
       self.searchBar.searchBarStyle = UISearchBarStyleMinimal;
       
       
       self.mainTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 40, ScreenWidth, ScreenHeight - 40 -64)];
       self.mainTable.delegate = self;
       self.mainTable.dataSource = self;
       self.mainTable.tableFooterView = [UIView new];
       
       [self.view addSubview:self.searchBar];
       [self.view addSubview:self.mainTable];
       
       
}

-(void)initLocation
{
    _locationManager = [[BMKLocationManager alloc] init];
    
    _locationManager.delegate = self;
    
    _locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
    _locationManager.pausesLocationUpdatesAutomatically = NO;
//    _locationManager.allowsBackgroundLocationUpdates = YES;
    _locationManager.locationTimeout = 10;
    _locationManager.reGeocodeTimeout = 10;
    
}

-(void)initBlock
{
    WeakSelf;
    self.completionBlock = ^(BMKLocation *location, BMKLocationNetworkState state, NSError *error)
    {
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            
            
        }
        
        if (location.location) {//得到定位信息，添加annotation
        

//            if (location.rgcData.poiList) {
//                for (BMKLocationPoi * poi in location.rgcData.poiList) {
//                    NSLog(@"poi = %@, %@, %f, %@, %@", poi.name, poi.addr, poi.relaiability, poi.tags, poi.uid);
//                }
//            }
//            if (location.rgcData.poiRegion) {
//                NSLog(@"poiregion = %@, %@, %@", location.rgcData.poiRegion.name, location.rgcData.poiRegion.tags, location.rgcData.poiRegion.directionDesc);
//            }
        }
        
        if (location.rgcData) {
            self->isLocating = YES;
            NSLog(@"rgc = %@",[location.rgcData description]);
            self->isLocationFail = NO;
            self->currentLocationCityName = location.rgcData.city;
        }else{
            self->isLocationFail = YES;
        }
        
        [ weakSelf reloadCollection];
        NSLog(@"netstate = %d",state);
    };
    
//    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(reloadCollection) userInfo:nil repeats:NO];
}

/**
 *  @brief 为了适配app store关于新的后台定位的审核机制（app store要求如果开发者只配置了使用期间定位，则代码中不能出现申请后台定位的逻辑），当开发者在plist配置NSLocationAlwaysUsageDescription或者NSLocationAlwaysAndWhenInUseUsageDescription时，需要在该delegate中调用后台定位api：[locationManager requestAlwaysAuthorization]。开发者如果只配置了NSLocationWhenInUseUsageDescription，且只有使用期间的定位需求，则无需在delegate中实现逻辑。
 *  @param manager 定位 BMKLocationManager 类。
 *  @param locationManager 系统 CLLocationManager 类 。
 *  @since 1.6.0
 */
- (void)BMKLocationManager:(BMKLocationManager * _Nonnull)manager doRequestAlwaysAuthorization:(CLLocationManager * _Nonnull)locationManager
{
    
    [locationManager requestAlwaysAuthorization];
}

//-(void)statLocation{
//    //开始定位，定位后签到
//    self.locManager.delegate = self;
//    if (IOS_8) {
//
//        [self.locManager requestWhenInUseAuthorization];
//
//    }
//    // 设置定位精度，十米，百米，最好
//    [self.locManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
//    [self.locManager startUpdatingLocation];
//
//    [self.geocoder reverseGeocodeLocation:self.locManager.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
//        [self.locManager stopUpdatingLocation];
//        self->isLocating = YES;
//        if (error || placemarks.count == 0) {
//            self->isLocationFail = YES;
//        }else{
//            self->isLocationFail = NO;
//            CLPlacemark *currentPlace = [placemarks firstObject];
//            self->currentLocationCityName = currentPlace.locality;
//        }
//        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(reloadCollection) userInfo:nil repeats:NO];
//    }];
//}

-(void)reloadCollection{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.collectionView reloadItemsAtIndexPaths:@[path]];
    });
}
-(void)returnVC{
    self.navigationController.navigationBar.hidden = YES;
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - UISearchBarDelegate
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    [self.searchData removeAllObjects];
    NSArray *ary = [NSArray new];
    ary = [ZYPinYinSearch searchWithOriginalArray:allCityNames andSearchText:searchText andSearchByPropertyName:@"cities"];
    if (searchText.length == 0) {
        [self.searchData addObjectsFromArray:allCityNames];
        _isSearch = NO;
    }else {
        [self.searchData addObjectsFromArray:ary];
        _isSearch = YES;
    }
    [self.mainTable reloadData];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    
    _searchBar.showsCancelButton = YES;
    
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    _searchBar.showsCancelButton = NO;
    [_searchBar resignFirstResponder];
    _searchBar.text = @"";
    _isSearch = NO;
    [_mainTable reloadData];
}

#pragma mark - UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (!_isSearch) {
        return allCities.count + 1;
    }else{
        return 1;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (!_isSearch) {
        if (section == 0) {
            return 1;
        }else{
            NSArray *cities = [LocationCityModel mj_objectArrayWithKeyValuesArray: allCities[section - 1][@"cities"]];
            return cities.count;
        }
    }else {
        return self.searchData.count;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
       if (section == 0) {
           return 0;
       }else{
           return  25;
       }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!_isSearch) {
        if (indexPath.section == 0) {
         float a = (hostCities.count/3==0?hostCities.count/3:hostCities.count/3+1)*40 + 40 + 60;
            return a;
        }else{
            return 44;
        }
    }else{
        return 44;
    }
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"cityCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    if (!_isSearch) {
        if (indexPath.section == 0 && indexPath.row == 0) {
            UITableViewCell *newCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"new"];
            [newCell addSubview:self.collectionView];
            return newCell;
        }else{
//            NSDictionary *dic = allCities[indexPath.section - 1];
            NSArray *cities = [LocationCityModel mj_objectArrayWithKeyValuesArray: allCities[indexPath.section - 1][@"cities"]];
            LocationCityModel * model = cities[indexPath.row];
            cell.textLabel.text = model.name;
        }
    }else{
        cell.textLabel.text = self.searchData[indexPath.row];
    }
    
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cityName = [NSString new];
    if (!_isSearch) {
        if (indexPath.section !=0) {
//            NSDictionary *dic = allCities[indexPath.section - 1];
            NSArray *cities = [LocationCityModel mj_objectArrayWithKeyValuesArray: allCities[indexPath.section - 1][@"cities"]];
            LocationCityModel * model = cities[indexPath.row];
            cityName = model.name;
        }
    }else{
        cityName = self.searchData[indexPath.row];
    }
    self.selectCity(cityName);
    
    [self returnVC];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (!_isSearch) {
        if (section == 0) {
              return nil;
        }else{
            UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.width, 25)];
            view.backgroundColor = [UIColor mainBackgroundColor];


            UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, view.width-20, view.height)];
            label.backgroundColor = [UIColor mainBackgroundColor];
            label.textColor = [UIColor blackColor];
            label.font = [UIFont systemFontOfSize:13];
            label.textAlignment = NSTextAlignmentLeft;
            
            NSString * testString = allCities[section - 1][@"title"];
            
            NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
            paraStyle.alignment = NSTextAlignmentLeft;//对齐
            paraStyle.headIndent = 0.0f;//行首缩进
            //字体大小号字乘以2 即首行空出两个字符
            CGFloat emptylen = 15;
            paraStyle.firstLineHeadIndent = emptylen;//首行缩进
//            paraStyle.tailIndent = 100.0f;//行尾缩进
//            paraStyle.lineSpacing = 2.0f;//行间距
            NSAttributedString *attrText = [[NSAttributedString alloc] initWithString:testString attributes:@{NSParagraphStyleAttributeName:paraStyle}];
            label.attributedText = attrText;
            
            [view addSubview:label];
            
            UIView * view2 = [[UIView alloc]initWithFrame:CGRectMake(label.width, 0, 20, view.height)];
            view.backgroundColor = [UIColor clearColor];
            [view addSubview:view2];

            
            return view;
        }
    } else {
          return nil;
    }

}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    if (!_isSearch) {
        if (section == 0) {
            return nil;
        }else{
            return allCities[section - 1][@"title"];
        }
    }else {
        return nil;
    }
}

-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    if (!_isSearch) {
        NSMutableArray *arr = [NSMutableArray new];
        for (NSDictionary *dic in allCities) {
            [arr addObject:dic[@"title"]];
        }
        return arr;
    }else {
        return nil;
    }
}
#pragma mark 索引列点击事件
-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    //点击索引，列表跳转到对应索引的行
    [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index+1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    [self showMessage:title toView:self.view];
    return index+1;
}

#pragma mark - UICollectionViewDelegate
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 2;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else{
        return hostCities.count;
    }
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CityCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionCellID forIndexPath:indexPath];
    if (!cell) {
        cell = [[CityCollectionCell alloc]initWithFrame:CGRectZero];
    }
    if (indexPath.section == 0) {
        cell.titleLabel.text = @"定位中...";
        cell.titleLabel.textAlignment = NSTextAlignmentLeft;
        CGRectSetX(cell.titleLabel.frame, cell.gpsImageView.frame.size.width +cell.gpsImageView.frame.origin.x+5);
        [cell.gpsImageView startAnimating];
        if (isLocating) {
            
            [cell isShowGPSStatus:isLocationFail withLocationCityName:currentLocationCityName];
        }
        
    }else{
        LocationCityModel * model = hostCities[indexPath.row];
        cell.titleLabel.text = model.name;
    }
    
    cell.backgroundColor = [UIColor whiteColor];
    [cell.layer setMasksToBounds: YES];
    [cell.layer setCornerRadius:cell.height/2];
    
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && !isLocationFail) {
        self.selectCity(currentLocationCityName);
    }else{
        self.selectCity(hostCities[indexPath.row]);
    }
    [self returnVC];
}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    NSString *reuseIdentifier;
    if ([kind isEqualToString: UICollectionElementKindSectionHeader ]){
        reuseIdentifier = collectionHeadID;
    }
    
    CityCollectionHeadView *view =  [collectionView dequeueReusableSupplementaryViewOfKind :kind   withReuseIdentifier:reuseIdentifier   forIndexPath:indexPath];
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]){
        if (indexPath.section == 0) {
            view.sectionTitleLabel.text = @"定位城市";
        }else{
            view.sectionTitleLabel.text = @"热门城市";
        }
    }
    
    return view;
}
//返回头headerView的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    return CGSizeMake(ScreenWidth, 30);
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return CGSizeMake(self.collectionView.frame.size.width/3, 30);
    }else{
        return CGSizeMake(self.collectionView.frame.size.width/3 - 20, 30);
    }
    
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                        layout:(UICollectionViewLayout *)collectionViewLayout
        insetForSectionAtIndex:(NSInteger)section {
    UICollectionViewFlowLayout *flowLayout =
    (UICollectionViewFlowLayout *)collectionViewLayout;
    flowLayout.minimumInteritemSpacing = 5;
    flowLayout.minimumLineSpacing = 5;
    return UIEdgeInsetsMake(5, 10, 5, 10);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark 显示一些信息
- (void)showMessage:(NSString *)message toView:(UIView *)view {
    if (view == nil) view = [[UIApplication sharedApplication].windows lastObject];
    // 快速显示一个提示信息
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
//    hud.labelText = message;
//    // 再设置模式
//    hud.mode = MBProgressHUDModeCustomView;
//
//    // 隐藏时候从父控件中移除
//    hud.removeFromSuperViewOnHide = YES;
//
//    // 1秒之后再消失
//    [hud hide:YES afterDelay:0.7];
}
@end
